package tech.dongling.boot.plugins.impl;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SM4;
import cn.hutool.json.JSONUtil;
import tech.dongling.boot.anno.Order;
import tech.dongling.boot.common.base.HttpBizRequest;
import tech.dongling.boot.plugins.RequestPlugin;

import java.util.Properties;

// 解密插件（@Order=10）
@Order(10)
public class DecryptPlugin implements RequestPlugin {
    private SM4 sm4;

    @Override
    public void init(Properties config) {
        if ("true".equals(config.getProperty("crypto.enabled"))) {
            String key = config.getProperty("crypto.sm4.key");
            sm4 = SmUtil.sm4(HexUtil.decodeHex(key));
        }
    }

    @Override
    public void process(HttpBizRequest request) throws Exception {
        if (sm4 != null && request.getBody() != null) {
            byte[] decrypted = sm4.decrypt(request.getBody().toString().getBytes());
            request.setBody(JSONUtil.parseObj(new String(decrypted)));
        }
    }
}